package com.csoa.community.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class IOUtils {
	private static final int BUFFER_SIZE = 1024;
	private static final byte[] buffer = new byte[BUFFER_SIZE];

	public static void copy(InputStream in, OutputStream out)
			throws IOException {
		while (true) {
			synchronized (buffer) {
				int count = in.read(buffer);
				if (count == -1) {
					break;
				}
				out.write(buffer, 0, count);
			}
		}
	}

	public interface MyDownloadListener {
		void onDownloading(int accepted, int expect);
	}

	public static void copy(InputStream in, OutputStream out,
			int contentLength, MyDownloadListener listener) throws IOException {
		byte[] responseBuffer = null;
		int perReadbuffer = BUFFER_SIZE * 10;
		if (contentLength > 0 && (contentLength / 10 > perReadbuffer)) {
			perReadbuffer = contentLength / 10;
		}
		responseBuffer = new byte[perReadbuffer];
		int ch = -1;
		int total = 0;
		while ((ch = in.read(responseBuffer)) != -1) {
			out.write(responseBuffer, 0, ch);
			total += ch;
			if (contentLength > 0) {
				if (listener != null) {
					listener.onDownloading(total, contentLength);
				}
			}
		}
	}

	public static String getFromAssets(InputStream inStream) {
		InputStreamReader inputReader = null;
		BufferedReader bufReader = null;
		String line = "";
		String Result = "";
		try {
			inputReader = new InputStreamReader(inStream);
			bufReader = new BufferedReader(inputReader);
			
			while ((line = bufReader.readLine()) != null) {
				Result += line;
			}
			return Result;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(inputReader != null) {
				try {
					inputReader.close();
					inputReader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
			if(bufReader != null) {
				try {
					bufReader.close();
					bufReader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
		return Result;
	}

}
